<template>
  <div class="meeting-room-management">
    <h2>会议室管理</h2>
    <div class="filter-bar">
      <input type="text" v-model="GetMeetingRoomNum.roomName" placeholder="请输入会议室名称" />
      <button class="primary-button" @click="SearchMeetingRoom()">查询</button>
      <button class="secondary-button" @click="ResetButton()">重置</button>
    </div>
    <div class="action-bar">
      <button class="primary-button" @click="dialogVisible = true, AddOrUpdate = 'false'">新增</button>
      <button class="danger-button" @click="DelRoomRangeWay">批量删除</button>
    </div>
    <!--数据展示-->
    <el-table :data="tableData" border>
      <el-table-column prop="" label="" width="50">
        <template v-slot="scope">
          <input type="checkbox" v-model="DelRoomRangeNum.roomIdList" :value="scope.row.meetingRoomId" />
        </template>
      </el-table-column>
      <el-table-column prop="meetingRoomName" label="会议室名称" width="350">
        <template v-slot="scope">
          <div class="room-name">
            <img v-if="scope.row.meetingRoomImg" style="width: 50%;height: 50%;"
              :src="'http://localhost:5070' + scope.row.meetingRoomImg" class="room-image" />
            <span>{{ scope.row.meetingRoomName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="capacityRange" label="容纳人数" />
      <el-table-column prop="location" label="会议室位置" />
      <el-table-column prop="administrator" label="管理员">
        <template v-slot="scope">
          <el-tag type="primary">{{ scope.row.administrator }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="contactPhone" label="联系电话" />
      <el-table-column prop="needReservationApproval" label="预约审批">
        <template v-slot="scope">
          <el-tag type="success" v-if="scope.row.needReservationApproval">是</el-tag>
          <el-tag type="danger" v-else>否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isSmartMeetingRoom" label="智能会议室">
        <template v-slot="scope">
          <el-tag type="success" v-if="scope.row.isSmartMeetingRoom">是</el-tag>
          <el-tag type="danger" v-else>否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="编辑">
        <template v-slot="scope">
          <el-text class="mx-1" @click="CheckTextButton(scope.row),
            dialogVisible = true" type="primary">查看</el-text>&nbsp;&nbsp;
          <el-text class="mx-1" type="success" @click="CheckTextButton(scope.row),
            dialogVisible = true, AddOrUpdate = 'true'">编辑</el-text>&nbsp;&nbsp;
          <el-text class="mx-1" @click="DelMeetingRoom(scope.row.meetingRoomId)" type="danger">删除</el-text>
        </template>
      </el-table-column>
    </el-table>
    <div class="footer-bar">
      <div class="batch-actions">
        <input type="checkbox" id="select-all-footer" v-model="selectAll" />
        <label for="select-all-footer">选择全部</label>
        <button class="secondary-button">反向选择</button>
        <button class="secondary-button">更多操作</button>
        <!--分页-->
        <div class="demo-pagination-block">
          <table>
            <tbody>
              <tr>
                <td>
                  <el-pagination v-model:current-page="pageData.pageIndex" v-model:page-size="pageData.pageSize"
                    :page-sizes="[2, 4, 6, 8]" :size="size" :disabled="disabled" :background="background"
                    layout="slot,total, sizes" :total="pageData.count" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页">
                    <span>共{{ pageData.pcount }}页，每页{{ GetMeetingRoomNum.pageSize }}条</span>
                  </el-pagination>
                </td>
                <td>
                  <el-pagination v-model:current-page="pageData.pageIndex" v-model:page-size="pageData.pageSize"
                    :page-sizes="[2, 4, 6, 8]" :size="size" :disabled="disabled" :background="background"
                    layout="slot, prev, pager, next" :total="pageData.count" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页">
                    <el-button @click="handleCurrentChange(pageData.pageIndex = 1)">首页</el-button>
                  </el-pagination>
                </td>
                <td>
                  <el-pagination v-model:current-page="pageData.pageIndex" v-model:page-size="pageData.pageSize"
                    :page-sizes="[2, 4, 6, 8]" :size="size" :disabled="disabled" :background="background"
                    layout="slot, jumper" :total="pageData.count" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页">
                    <el-button @click="handleCurrentChange(pageData.pageIndex = pageData.pcount)">尾页</el-button>
                  </el-pagination>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
  <!--弹出层-->
  <el-dialog v-model="dialogVisible" title="新增会议室" width="900px" :before-close="handleClose">
    <span>
      <!-- 表单内容 -->
      <div class="TablesInfo">
        <div class="tableleft">
          <el-form ref="ruleFormRef" style="width: 500px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="会议名称" prop="meetingRoomName">
              <el-input v-model="ruleForm.meetingRoomName" />
            </el-form-item>
            <el-form-item label="容纳人数" prop="capacityRange">
              <el-select v-model="ruleForm.capacityRange" placeholder="请输入容纳人数">
                <el-option label="10~20人" value="10~20人" />
                <el-option label="21~40人" value="21~40人" />
                <el-option label="41~70人" value="41~70人" />
                <el-option label="71~100人" value="71~100人" />
              </el-select>
            </el-form-item>
            <el-form-item label="会议室位置" prop="location">
              <el-select v-model="ruleForm.location" placeholder="请输入会议室位置">
                <el-option label="办公楼-601" value="办公楼-601" />
                <el-option label="办公楼-602" value="办公楼-602" />
                <el-option label="办公楼-603" value="办公楼-603" />
                <el-option label="办公楼-604" value="办公楼-604" />
              </el-select>
            </el-form-item>
            <el-form-item label="会议室管理员" prop="administrator">
              <el-input v-model="ruleForm.administrator" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="ruleForm.contactPhone" />
            </el-form-item>
            <el-form-item label="" prop="">
              <el-checkbox-group v-model="checkboxruleForm.checkNode1">
                <el-checkbox value="1" name="">
                  预约审批
                </el-checkbox>
              </el-checkbox-group>
              <el-checkbox-group v-model="checkboxruleForm.checkNode2">
                <el-checkbox value="2" name="">
                  智能会议室
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </div>
        <!--图片上传-->
        <div class="tableright">
          <el-upload class="avatar-uploader" action="http://localhost:5070/api/v1/UpFile/UpLoadnew"
            :show-file-list="false" :on-success="handleAvatarSuccess">
            <img v-if="ruleForm.meetingRoomImg" style="width: 100%;height: 100%;"
              :src="'http://localhost:5070' + ruleForm.meetingRoomImg" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </div>
      </div>
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">退出</el-button>
        <el-button type="primary" v-if="AddOrUpdate == 'false'" @click="dialogVisible = false, submitForm(ruleFormRef)">
          确定
        </el-button>
        <el-button type="primary" v-if="AddOrUpdate == 'true'"
          @click="dialogVisible = false, UpdateMeetingRoom(ruleForm)">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
// 导入 ref 函数
import { ElMessage } from 'element-plus'
import { ref, reactive, watch, onMounted } from 'vue'
import { AddMeetRoom, GetMeetRoom, DeleteMeetRoom, UpdateMeetRoom, DeleteMeetRoomRange } from '../../api/meetingroom'
import { ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { checkNode } from 'element-plus/es/components/cascader-panel/src/utils.mjs'
import type { ComponentSize } from 'element-plus'
import { useCounterStore } from '@/stores/counter'
// 页面加载时获取数据
onMounted(() => {
  GetMeetingRoom()
})
// 定义表格数据
const tableData = ref([{
  "meetingRoomId": 2,
  "meetingRoomImg": "/pic/89fad7a6-002c-4fba-8fca-feb66c8490b9SunFragment7_8k_bd46f.jpg",
  "meetingRoomName": "办公室大楼会议室",
  "capacityRange": "21~40人",
  "location": "办公楼-601",
  "administrator": "张三",
  "contactPhone": "19878789990",
  "needReservationApproval": false,
  "isSmartMeetingRoom": true,
  "isDeleted": true
}])
// 表单引用
const ruleFormRef = ref<FormInstance>()
// 对话框状态
const dialogVisible = ref(false)
// 用于区分新增或更新操作
const AddOrUpdate = ref('false')
// 分页相关参数
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
const route = useCounterStore();
// 表单数据
const ruleForm = reactive({
  meetingRoomId: 0,
  meetingRoomImg: "",
  meetingRoomName: "",
  capacityRange: "",
  location: "",
  administrator: "",
  contactPhone: "",
  needReservationApproval: false,
  isSmartMeetingRoom: false,
  isDeleted: false,
  operatorName: route.userInfo.idNumber
})
//定义多选框数据类型
const checkboxruleForm = reactive({
  checkNode1: [],
  checkNode2: []
})
//定义分页数据
const pageData = ref({
  pageIndex: 1,
  pageSize: 2,
  count: 0,
  pcount: 0
})
//批量删除参数
const DelRoomRangeNum = ref({
  roomIdList: [],
  operatorName: route.userInfo.idNumber
})
//一键全选属性
const selectAll = ref(false)
// 定义查询参数
const GetMeetingRoomNum = reactive({
  roomName: "",
  pageIndex: 1,
  pageSize: 2
})
// 监听对话框状态变化，重置表单
watch(() => dialogVisible.value, (newVal) => {
  // ...
  //关闭对话框时重置表单
  if (dialogVisible.value === false) {
    ruleForm.meetingRoomImg = ""
    ruleForm.meetingRoomName = ""
    ruleForm.capacityRange = ""
    ruleForm.location = ""
    ruleForm.administrator = ""
    ruleForm.contactPhone = ""
    ruleForm.needReservationApproval = false
    ruleForm.isSmartMeetingRoom = false
    ruleForm.isDeleted = false
    checkboxruleForm.checkNode1 = [] // 重置多选框
    AddOrUpdate.value = ''
  } else if (dialogVisible.value === true) {
    watch(
      () => checkboxruleForm.checkNode1,
      (value: any) => {
        //console.log(value)
        for (let i = 0; i < value.length; i++) {
          if (value == 1) {
            ruleForm.needReservationApproval = true
          } else {
            ruleForm.isSmartMeetingRoom = true
          }
        }
      },
      { immediate: true }
    )
  }
  //弹框中保存还是新增
  if (AddOrUpdate.value == 'true') {
    return
  }
})
//获取会议室列表
const GetMeetingRoom = async () => {
  try {
    const way = await GetMeetRoom(GetMeetingRoomNum)
    tableData.value = way.data.data.data
    pageData.value.count = way.data.data.count
    pageData.value.pcount = way.data.data.pcount
    //刷新页面时，批量删除选择框清空
    DelRoomRangeNum.value.roomIdList = []
    //console.log(pageData)
  } catch (error) {

  }
}
// 关闭对话框时的处理逻辑
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确定要关闭吗?')
    .then(() => {
      dialogVisible.value = false
      // 重置表单
      ruleForm.meetingRoomImg = ""
      ruleForm.meetingRoomName = ""
      ruleForm.capacityRange = ""
      ruleForm.location = ""
      ruleForm.administrator = ""
      ruleForm.contactPhone = ""
      ruleForm.needReservationApproval = false
      ruleForm.isSmartMeetingRoom = false
      ruleForm.isDeleted = false
      checkboxruleForm.checkNode1 = [] // 重置多选框
      done() // 调用 done 函数关闭对话框
    })
    .catch(() => {
      // catch error
    })
}
// 定义表单验证规则
const rules = reactive<FormRules>({
  meetingRoomName: [
    { required: true, message: '请输入会议室名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符之间', trigger: 'blur' }
  ],
  capacityRange: [
    { required: true, message: '请选择容纳人数', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请选择会议室位置', trigger: 'blur' }
  ],
  administrator: [
    { required: true, message: '请输入会议室管理员', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
})
// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  const way = await AddMeetRoom(ruleForm)
  if (way.data.code == 200) {
    ElMessage.success(way.data.message)
  } else {
    ElMessage.error(way.data.message)
  }
}
// 处理上传成功的图片
const handleAvatarSuccess = (data: any) => {
  console.log(data)
  if (data.isSuc) {
    ElMessage.success(data.message)
    ruleForm.meetingRoomImg = data.msg
  } else {
    ElMessage.error(data.msg)
  }

}
// 处理查看会议室详情
const CheckTextButton = (value: any) => {
  ruleForm.meetingRoomId = value.meetingRoomId
  ruleForm.meetingRoomName = value.meetingRoomName
  ruleForm.capacityRange = value.capacityRange
  ruleForm.location = value.location
  ruleForm.administrator = value.administrator
  ruleForm.contactPhone = value.contactPhone
  ruleForm.meetingRoomImg = value.meetingRoomImg
  ruleForm.needReservationApproval = value.needReservationApproval
  ruleForm.isSmartMeetingRoom = value.isSmartMeetingRoom
  ruleForm.isDeleted = value.isDeleted
}
//删除会议室
const DelMeetingRoom = async (value: any) => {
  ElMessageBox.confirm('确定要删除该会议室吗?')
    .then(async () => {
      // 调用删除接口
      // 这里可以添加删除逻辑
      const way = await DeleteMeetRoom({
        meetingRoomId: value,
        operatorName: route.userInfo.idNumber
      })
      if (way.data.code == 200) {
        ElMessage.success(way.data.message)
        GetMeetingRoom() // 刷新会议室列表
      } else {
        ElMessage.error(way.data.message)
      }

    })
    .catch(() => {
      // 用户取消删除操作
    })
}
//更新会议室信息
const UpdateMeetingRoom = async (value: any) => {
  const way = await UpdateMeetRoom(value)
  console.log(way)
  if (way.data.code == 200) {
    ElMessage.success(way.data.msg)
    GetMeetingRoom() // 刷新会议室列表
  } else {
    ElMessage.error(way.data.msg)
  }
}
//条件查询
const SearchMeetingRoom = () => {
  GetMeetingRoom()
}
//重置按钮
const ResetButton = () => {
  GetMeetingRoomNum.roomName = ""
  GetMeetingRoomNum.pageIndex = 1
  GetMeetingRoomNum.pageSize = 10
  GetMeetingRoom()
}
//分页
// 每页显示条数改变时触发
const handleSizeChange = (val: number) => {
}
// 分页当前页改变时触发
const handleCurrentChange = (val: number) => {
}
//监听分页数据变化
watch((pageData), () => {
  GetMeetingRoomNum.pageIndex = pageData.value.pageIndex
  GetMeetingRoomNum.pageSize = pageData.value.pageSize
  GetMeetingRoom()
}, { deep: true })
//监听全选框变化
watch(() => selectAll.value, () => {
  if (selectAll.value) {
    for (let i = 0; i < tableData.value.length; i++) {
      DelRoomRangeNum.value.roomIdList.push((tableData.value[i].meetingRoomId) as never)
    }
  } else {
    DelRoomRangeNum.value.roomIdList = []
  }
})
//批量删除会议室
const DelRoomRangeWay = async () => {
  ElMessageBox.confirm('确定要删除这些会议室吗?')
    .then(async () => {
      const way = await DeleteMeetRoomRange(DelRoomRangeNum.value)
      if (way.data.isSuc) {
        ElMessage.success("批量删除成功")
        GetMeetingRoom() // 刷新会议室列表
      } else {
        ElMessage.error('批量删除失败')
      }
    })
    .catch(() => {
      // 用户取消删除操作
    })
}

</script>

<style scoped>

.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

.tableright {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 200px;
  height: 200px;
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 10px;
  background-color: #fff;
}

.TablesInfo {
  position: relative;
  min-height: 340px;
}


.meeting-room-management {
  padding: 20px;
  font-family: 'Microsoft YaHei', sans-serif;
  color: #333;
  background-color: #f5f7fa;
  /* 模仿背景色 */
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin: 20px;
}

h2 {
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
}

.filter-bar,
.action-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.filter-bar input[type="text"] {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 200px;
}

button {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s, color 0.3s;
}

.primary-button {
  background-color: #409eff;
  color: white;
}

.primary-button:hover {
  background-color: #66b1ff;
}

.secondary-button {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
}

.secondary-button:hover {
  background-color: #ecf5ff;
  color: #409eff;
  border-color: #c6e2ff;
}

.danger-button {
  background-color: #f56c6c;
  color: white;
}

.danger-button:hover {
  background-color: #f78989;
}


.data-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
  background-color: #fff;
}

.data-table th,
.data-table td {
  border-bottom: 1px solid #ebeef5;
  padding: 12px 15px;
  text-align: left;
  font-size: 14px;
}

.data-table th {
  background-color: #f5f7fa;
  font-weight: 600;
  color: #909399;
}

.data-table td {
  color: #606266;
  vertical-align: middle;
  /* 垂直居中 */
}

.room-name {
  display: flex;
  align-items: center;
}

.room-image {
  width: 60px;
  height: 40px;
  margin-right: 10px;
  border-radius: 4px;
  object-fit: cover;
}

.action-link {
  color: #409eff;
  text-decoration: none;
  margin-right: 10px;
  cursor: pointer;
}

.action-link:hover {
  text-decoration: underline;
}

.action-link.danger {
  color: #f56c6c;
}

.action-link.danger:hover {
  color: #f78989;
}


.footer-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 10px 0;
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  color: #606266;
}

.batch-actions input[type="checkbox"] {
  margin-right: 5px;
}


.pagination {
  display: flex;
  align-items: center;
  gap: 5px;
}

.pagination button {
  min-width: 30px;
  height: 30px;
  padding: 0 10px;
  background-color: #f4f4f5;
  color: #606266;
  border: 1px solid #e4e7ed;
  cursor: pointer;
}

.pagination button:hover {
  color: #409eff;
}

.pagination button.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination button:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
  background-color: #f4f4f5;
}

.pagination span {
  margin: 0 5px;
  color: #606266;
}
</style>